import play.api.libs.json.Json
import play.api.mvc.{AcceptExtractors, ActionBuilderImpl, BodyParser, Rendering, Request, Result, Results}
import utiliy.RequestHelper._
import scala.concurrent.{ExecutionContext, Future}

package object controllers {

  def checkLogin[A](implicit parser: BodyParser[A], ec: ExecutionContext, permission: String = "login"): ActionBuilderImpl[A] = new ActionBuilderImpl(parser) with Rendering with AcceptExtractors {
    override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
      if (isLogin(permission)(request)) {
        block(request)
      } else {
        Future.successful {
          render {
            case Accepts.Html() => {
              val result = Results.Redirect(routes.UsersController.login())
                .flashing("success" -> "您尚未登录，无权执行该操作！")
              val accid = request.session.get("accid")
              if (accid.nonEmpty) result
              else result.withSession(request.session + ("surl" -> request.uri))
            }
            //              Results.Ok(views.html.message("系统提示", "您尚未登录，无权执行该操作！")(request))
            case Accepts.Json() => Results.Ok(Json.obj("status" -> 1, "msg" -> "您尚未登录，无权执行该操作！"))
          }(request)
        }
      }
    }
  }

  def checkAdmin[A](implicit parser: BodyParser[A], ec: ExecutionContext): ActionBuilderImpl[A] = new ActionBuilderImpl(parser) with Rendering with AcceptExtractors {
    override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
      if (isAdmin(request)) {
        block(request)
      } else {
        Future.successful {
          render {
            case Accepts.Html() => Results.Redirect(routes.UsersController.index())
              .flashing("success" -> "您不是管理员，无权执行该操作！")
              .withSession(request.session + ("surl" -> request.uri))
            //              Results.Ok(views.html.message("系统提示", "您尚未登录，无权执行该操作！")(request))
            case Accepts.Json() => Results.Ok(Json.obj("status" -> 1, "msg" -> "您不是管理员，无权执行该操作！"))
          }(request)
        }
      }
    }
  }

}
